/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.correct;

import com.wtkj.vo.dzzf.base.kfwd.CardInfo;
import com.wttech.dzzf.process.dao.DataInitilizingDao;
import com.wttech.dzzf.process.model.user.Card;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import com.wttech.dzzf.process.util.BusinessUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import static com.wttech.dzzf.process.constant.UserConstants.DEFAULT_PROCESS_NUM;

/**
 * 纠正USERID
 *
 * @author MaShibo
 * @date 2017/12/14.
 */
@Service
public class CorrectErrorUserId {

	private static final Logger LOGGER = LoggerFactory.getLogger(CorrectErrorUserId.class);

	@Resource
	private DataInitilizingDao dataInitilizingDao;

	@Resource
	private BaseInfoService baseInfoService;

	@Resource
	private ThreadPoolTaskExecutor executor;

	private Integer selectValue;

	private void process() {
		if (selectValue == null) {
			LOGGER.info("请先选择要生成第几阶段的数据");
			return;
		}
		LOGGER.info("正在查询待处理资金账户总数量");
		int total = dataInitilizingDao.queryCardInfoNum();
		LOGGER.info("共{}条资金账户信息待处理", total);
		int perNum = total / 3;
		LOGGER.info("每个阶段约处理{}条数据", perNum);
		int startTotalRow = (selectValue - 1) * perNum + 1;
		int endTotalRow = selectValue * perNum;
		if (endTotalRow > total) {
			endTotalRow = total;
		}
		LOGGER.info("已选择处理第{}阶段数据", selectValue);
		LOGGER.info("起始总行号【{}】，终止总行号【{}】", startTotalRow, endTotalRow);
		int perTotal = endTotalRow - startTotalRow + 1;
		LOGGER.info("该阶段要处理{}条数据", perTotal);
		int count = (int) Math.ceil((double) perTotal / DEFAULT_PROCESS_NUM);
		LOGGER.info("该阶段每个线程处理每次处理{}条数据，共需要处理{}次", DEFAULT_PROCESS_NUM, count);
		List<Future<Void>> futures = new ArrayList<>(count);
		for (int i = 0; i < count; i++) {
			int startRow = startTotalRow + DEFAULT_PROCESS_NUM * i;
			int endRow = startTotalRow + DEFAULT_PROCESS_NUM * (i + 1) - 1;
			int finalEndRow = i == count - 1 ? total : endRow;
			futures.add(executor.submit(() -> {
				processOnce(startRow, finalEndRow);
				return null;
			}));
		}
		baseInfoService.getFutureResult(futures);
		LOGGER.info("数据处理完毕");
		executor.shutdown();
	}

	private void processOnce(int startRow, int endRow) {
		LOGGER.info("开始处理，第【{}】行至第【{}】行的数据", startRow, endRow);
		List<Card> cardInfos = dataInitilizingDao.queryCardInfosByRow(startRow, endRow);
		cardInfos.forEach(cardInfo -> {
			try {
				processCardInfo(cardInfo);
			} catch (Exception e) {
				LOGGER.error(e.getMessage(), e);
			}
		});
		LOGGER.info("第【{}】行至第【{}】行的数据，处理完成", startRow, endRow);
	}

	private void processCardInfo(Card cardInfo) {
		String cardId = cardInfo.getId();
		CardInfo dzzfCard = dataInitilizingDao.queryCardInfoByNo(cardId.substring(4));
		if (dzzfCard == null) {
			LOGGER.error("卡片【{}】找不到对应信息", cardId);
			return;
		}
		Integer newCardType = BusinessUtils.determineCardType(dzzfCard.getECardType(), dzzfCard.getBindAccountType(), dzzfCard.getBindCardType());
		Integer cardType = newCardType == null  ? BusinessUtils.determineCardType(dzzfCard.getTopClass(), dzzfCard.getECardType()) : newCardType;
		dataInitilizingDao.updateBsCardType(cardInfo.getId(), cardType);
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		CorrectErrorUserId service = context.getBean(CorrectErrorUserId.class);
		service.selectValue = Integer.valueOf(args[0]);
		service.process();
	}
}
